/**
 * Copyright &copy; 2017-2020 <a href="http://www.fosung.com/">FosungFrame</a> All rights reserved.
 */
package com.fosung.frame.modules.life.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fosung.frame.common.config.Global;
import com.fosung.frame.common.persistence.Page;
import com.fosung.frame.common.utils.StringUtils;
import com.fosung.frame.common.web.BaseController;
import com.fosung.frame.modules.assessment.entity.AssessmentTime;
import com.fosung.frame.modules.assessment.service.AssessmentTimeService;
import com.fosung.frame.modules.checkinfos.entity.Checkinfos;
import com.fosung.frame.modules.checkinfos.service.CheckinfosService;
import com.fosung.frame.modules.life.entity.OrganizeLife;
import com.fosung.frame.modules.life.entity.OrganizeLifeType;
import com.fosung.frame.modules.life.service.OrganizeLifeService;
import com.fosung.frame.modules.life.service.OrganizeLifeTypeService;
import com.fosung.frame.modules.partyassessmentinfo.entity.PartyAssessmentInfo;
import com.fosung.frame.modules.partyassessmentinfo.service.PartyAssessmentInfoService;
import com.fosung.frame.modules.partysinfo.entity.PartysInfo;
import com.fosung.frame.modules.partysinfo.service.PartysInfoService;
import com.fosung.frame.modules.personassessmentinfo.entity.PersonAssessmentInfo;
import com.fosung.frame.modules.personassessmentinfo.service.PersonAssessmentInfoService;
import com.fosung.frame.modules.score.dao.OrganizePersonDetailDao;
import com.fosung.frame.modules.score.entity.OrganizePersonDetail;
import com.fosung.frame.modules.score.entity.PartyScoreDetail;
import com.fosung.frame.modules.score.entity.PersonScoreDetail;
import com.fosung.frame.modules.score.service.PartyScoreDetailService;
import com.fosung.frame.modules.score.service.PersonScoreDetailService;
import com.fosung.frame.modules.sys.utils.UserUtils;

/**
 * 组织生活管理Controller
 * 
 * @author zhangfn
 * @version 2017-08-29
 */
@Controller
@RequestMapping(value = "${adminPath}/life/organizeLifeQd")
public class OrganizeLifeQdController extends BaseController {

	@Autowired
	private OrganizeLifeService organizeLifeService;
	@Autowired
	private OrganizeLifeTypeService organizeLifeTypeService;
	@Autowired
	private CheckinfosService checkinfosService;
	@Autowired
	private AssessmentTimeService assessmentTimeService;
	@Autowired
	private PartyAssessmentInfoService partyAssessmentInfoService;
	@Autowired
	private PersonAssessmentInfoService personAssessmentInfoService;
	@Autowired
	private PartyScoreDetailService partyScoreDetailService;
	@Autowired
	private PersonScoreDetailService personScoreDetailService;
	@Autowired
	private OrganizePersonDetailDao organizePersonDetailDao;
	@Autowired
	private PartysInfoService partysInfoService;

	@ModelAttribute
	public OrganizeLife get(@RequestParam(required = false) String id) {
		OrganizeLife entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = organizeLifeService.get(id);
		}
		if (entity == null) {
			entity = new OrganizeLife();
		}
		return entity;
	}

	@RequiresPermissions("life:organizeLifeQd:view")
	@RequestMapping(value = { "list", "" })
	public String list(OrganizeLife organizeLife, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		organizeLife.setJhstate("3");
		organizeLife.setJhstate1("7");
		organizeLife.setShstate("1");
		organizeLife.setShstate1("5");
		organizeLife.setColumn25("0");
		organizeLife.setOrganizationid(UserUtils.getUser().getOffice().getId());
		Page<OrganizeLife> page = organizeLifeService.findPage(new Page<OrganizeLife>(request, response), organizeLife);
		// 给首页组织生活分类下拉框赋值
		OrganizeLifeType type = new OrganizeLifeType();
		type.setDelFlag("0");
		type.setHasChildren("0");
		type.setOrgId(UserUtils.getUser().getOffice().getId());
		List<OrganizeLifeType> organizeLifeTypes = organizeLifeTypeService.findList(type);
		model.addAttribute("organizeLifeTypes", organizeLifeTypes);
		// 因为组织生活分类可能包括多个，这里先spilt再单独查询拼成字符串显示到前台list

		List<OrganizeLife> olList = page.getList();

		if (olList.size() > 0) {
			for (int i = 0; i < olList.size(); i++) {
				StringBuffer typeNames = new StringBuffer();
				OrganizeLife o = olList.get(i);
				if (o.getTypeids() != null && !o.getTypeids().equals("")) {
					String[] types = o.getTypeids().split(",");

					if (types != null && types.length > 0) {
						for (String s : types) {
							// 循环遍历数组中元素，添加到StringBuilder 对象中
							String t = organizeLifeTypeService.get(s).getTypename();
							typeNames.append(t + ",");
						}
					}
					if (typeNames.length() > 0) {
						// 调用字符串的deleteCharAt()方法,删除最后一个多余的逗号
						typeNames.deleteCharAt(typeNames.length() - 1);
					}

				}
				o.setTypeids(typeNames.toString());
			}
		}

		model.addAttribute("page", page);
		return "modules/life/organizeLifeQdList";
	}

	// 签到list页面查看详情
	@RequiresPermissions("life:organizeLifeQd:view")
	@RequestMapping(value = "form")
	public String form(OrganizeLife organizeLife, Model model) throws ParseException {

		PartysInfo p = partysInfoService.getByOrgid(UserUtils.getUser().getOffice().getId());
		if (p == null) {
			return "modules/error";
		} else {

			OrganizeLife organizeLife1 = organizeLifeService.get(organizeLife.getId());
			// 循环获取审批意见，然后赋值
			Checkinfos ci = new Checkinfos();
			ci.setOrganizeLifeId(organizeLife.getId());
			List<Checkinfos> listCheckinfos = checkinfosService.findList(ci);
			if (listCheckinfos.size() > 0) {
				String str = "";
				for (Checkinfos s : listCheckinfos) {
					Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK)
							.parse(s.getCreateDate().toString());
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					String sDate = sdf.format(date);

					str += "审核时间：" + sDate + ",审核人：" + s.getApproveUserId() + ",审核意见:" + s.getApproveContent() + "\n";
				}
				organizeLife1.setShyj(str);
			}
			List<OrganizeLifeType> listStr = new ArrayList();
			if (organizeLife1.getTypeids() != null && !organizeLife1.getTypeids().equals("")) {
				String[] types = organizeLife1.getTypeids().split(",");

				if (types != null && types.length > 0) {
					for (String s : types) {
						// 循环遍历数组中元素，添加到StringBuilder 对象中
						OrganizeLifeType o = new OrganizeLifeType();
						String t = organizeLifeTypeService.get(s).getTypename();
						o.setTypename(t);
						listStr.add(o);
					}
					model.addAttribute("listStr", listStr);
				}

			}

			model.addAttribute("organizeLife", organizeLife1);
			return "modules/life/organizeLifeQdForm";
		}

	}

	// 跳转到签到页面
	@RequiresPermissions("life:organizeLifeQd:view")
	@RequestMapping(value = "personQd")
	public String personQd(OrganizeLife organizeLife, Model model) {

		OrganizeLife organizeLife1 = organizeLifeService.get(organizeLife.getId());
		// 获取年份list
		AssessmentTime assessmentTime = new AssessmentTime();
		assessmentTime.setState("1");
		assessmentTime.setDelFlag("0");
		List<AssessmentTime> assessmentTimeList = assessmentTimeService.findList(assessmentTime);

		int personCount = organizePersonDetailDao.getPersonCount(organizeLife.getId());
		if (personCount == 0) {
			Map map = organizeLifeService.getQd("1");
			if (map != null) {
				model.addAttribute("partyAssessmentInfoList", map.get("partyAssessmentInfoList"));
				model.addAttribute("personAssessmentInfoList", map.get("personAssessmentInfoList"));
			}

			model.addAttribute("organizeLife", organizeLife1);
			model.addAttribute("assessmentTimeList", assessmentTimeList);

			return "modules/life/personQd";
		} else {
			Map map = organizeLifeService.upQd(organizeLife.getId());
			if (map != null) {
				model.addAttribute("partyScoreDetailList", map.get("partyScoreDetailList"));
				model.addAttribute("personScoreDetailList", map.get("personScoreDetailList"));
				model.addAttribute("organizePersonDetailList", map.get("organizePersonDetailList"));
			}
			Map mapSelect = organizeLifeService.getQd("1");// 获取所有的下拉框的值
			if (mapSelect != null) {
				model.addAttribute("partyAssessmentInfoList", mapSelect.get("partyAssessmentInfoList"));
				model.addAttribute("personAssessmentInfoList", mapSelect.get("personAssessmentInfoList"));
			}

			model.addAttribute("organizeLife", organizeLife1);
			model.addAttribute("assessmentTimeList", assessmentTimeList);
			return "modules/life/upPersonQd";
		}

	}

	@RequiresPermissions("life:organizeLifeQd:edit")
	@RequestMapping(value = "save")
	public String save(OrganizeLife organizeLife, Model model, RedirectAttributes redirectAttributes)
			throws ParseException {
		if (!beanValidator(model, organizeLife)) {
			return form(organizeLife, model);
		}
		organizeLifeService.save(organizeLife);
		addMessage(redirectAttributes, "保存组织生活管理成功");
		return "redirect:" + Global.getAdminPath() + "/life/organizeLifeQd/?repage";
	}

	@RequiresPermissions("life:organizeLifeQd:edit")
	@RequestMapping(value = "delete")
	public String delete(OrganizeLife organizeLife, RedirectAttributes redirectAttributes) {
		organizeLifeService.delete(organizeLife);
		addMessage(redirectAttributes, "删除组织生活管理成功");
		return "redirect:" + Global.getAdminPath() + "/life/organizeLifeQd/?repage";
	}

	// 根据id获取党组织积分内容
	@ResponseBody
	@RequestMapping(value = "/queryPartyAssessmentInfo/{id}", method = RequestMethod.GET)
	public PartyAssessmentInfo queryPartyAssessmentInfo(@PathVariable("id") String id) {
		PartyAssessmentInfo p = new PartyAssessmentInfo();
		p.setId(id);
		p = partyAssessmentInfoService.get(p);
		PartyScoreDetail partyScoreDetail = new PartyScoreDetail();
		partyScoreDetail.setOrganizeId(UserUtils.getUser().getOffice().getId());
		partyScoreDetail.setPartyAssessmentInfoId(id);
		PartyScoreDetail partyAppCount = partyScoreDetailService.getSqcs(partyScoreDetail);
		if (partyAppCount.getApplyCount() == null || partyAppCount.getApplyCount().equals("")) {
			p.setApplyCount("0");
		} else {
			p.setApplyCount(String.valueOf(partyAppCount.getApplyCount()));
		}
		return p;
	}

	// 根据id获取党员积分内容
	@ResponseBody
	@RequestMapping(value = "/queryPersonAssessmentInfo/{id}", method = RequestMethod.GET)
	public PersonAssessmentInfo queryPersonAssessmentInfo(@PathVariable("id") String id) {
		PersonAssessmentInfo p = new PersonAssessmentInfo();
		p.setId(id);
		p = personAssessmentInfoService.get(p);
		PersonScoreDetail personScoreDetail = new PersonScoreDetail();
		personScoreDetail.setOrganizeId(UserUtils.getUser().getOffice().getId());
		personScoreDetail.setPersonAssessmentInfoId(id);
		PersonScoreDetail appCount = personScoreDetailService.getSqcs(personScoreDetail);
		if (appCount.getApplyCount() == null || appCount.getApplyCount().equals("")) {
			p.setApplyCount("0");
		} else {
			p.setApplyCount(String.valueOf(appCount.getApplyCount()));
		}
		return p;
	}

	@RequestMapping(value = "qd")
	@ResponseBody
	public Map<String, String> qd(@RequestBody OrganizeLife organizeLife, Model model,
			RedirectAttributes redirectAttributes) {

		for (int i = 0; i < organizeLife.getPartyScoreDetailList().size(); i++) {
			organizeLife.getPartyScoreDetailList().get(i).setOrganizeId(UserUtils.getUser().getOffice().getId());
		}
		for (int i = 0; i < organizeLife.getPersonScoreDetailList().size(); i++) {
			organizeLife.getPersonScoreDetailList().get(i).setOrganizeId(UserUtils.getUser().getOffice().getId());
		}
		List<List<OrganizePersonDetail>> lists = organizeLife.getOrganizePersonDetailList();

		for (int i = 0; i < lists.size(); i++) {

			for (int y = 0; y < lists.get(i).size(); y++) {
				OrganizePersonDetail o = lists.get(i).get(y);
				o.setOrganizeId(UserUtils.getUser().getOffice().getId());
			}
		}

		Map<String, String> map = new HashMap<String, String>();
		organizeLifeService.qd(organizeLife);
		map.put("type", "success");
		map.put("msg", "添加成功！");
		return map;

	}

	@RequestMapping(value = "upqd")
	@ResponseBody
	public Map<String, String> upqd(@RequestBody OrganizeLife organizeLife, Model model,
			RedirectAttributes redirectAttributes) {
		for (int i = 0; i < organizeLife.getPartyScoreDetailList().size(); i++) {
			organizeLife.getPartyScoreDetailList().get(i).setOrganizeId(UserUtils.getUser().getOffice().getId());
		}
		for (int i = 0; i < organizeLife.getPersonScoreDetailList().size(); i++) {
			organizeLife.getPersonScoreDetailList().get(i).setOrganizeId(UserUtils.getUser().getOffice().getId());
		}
		List<List<OrganizePersonDetail>> lists = organizeLife.getOrganizePersonDetailList();

		for (int i = 0; i < lists.size(); i++) {

			for (int y = 0; y < lists.get(i).size(); y++) {
				OrganizePersonDetail o = lists.get(i).get(y);
				o.setOrganizeId(UserUtils.getUser().getOffice().getId());
			}
		}

		Map<String, String> map = new HashMap<String, String>();
		organizeLifeService.upqd(organizeLife);
		map.put("type", "success");
		map.put("msg", "保存成功！");
		return map;

	}

	// 签到提交
	@ResponseBody
	@RequestMapping(value = "organizeLifeTj")
	public Map<String, String> organizeLifeTj(@RequestBody OrganizeLife organizeLife,
			RedirectAttributes redirectAttributes) throws ParseException {
		Map<String, String> map = new HashMap<String, String>();

		int personCount = organizePersonDetailDao.getPersonCount(organizeLife.getId());
		if (personCount > 0) {
			organizeLife.setJhstate("7");
			organizeLife.setShstate("2");

			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String d = format.format(organizeLife.getStarttime());
			Date sdate = format.parse(d);
			organizeLife.setStarttime(sdate);

			String e = format.format(organizeLife.getEndtime());
			Date edate = format.parse(e);
			organizeLife.setEndtime(edate);

			organizeLifeService.upState(organizeLife);
			map.put("type", "success");
			map.put("msg", "组织生活提交成功！");
		} else {
			map.put("type", "error1");
			map.put("msg", "请先签到！");
		}

		return map;
	}

	// 签到保存
	@ResponseBody
	@RequestMapping(value = "organizeLifeSave")
	public Map<String, String> organizeLifeSave(@RequestBody OrganizeLife organizeLife,
			RedirectAttributes redirectAttributes) throws ParseException {
		Map<String, String> map = new HashMap<String, String>();

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String d = format.format(organizeLife.getStarttime());
		Date sdate = format.parse(d);
		organizeLife.setStarttime(sdate);

		String e = format.format(organizeLife.getEndtime());
		Date edate = format.parse(e);
		organizeLife.setEndtime(edate);

		organizeLifeService.upState(organizeLife);
		map.put("type", "success");
		map.put("msg", "组织生活保存成功！");

		return map;
	}

	// 查看党组织和党员积分说明
	@ResponseBody
	@RequestMapping(value = "getPartyAssessmentInfo/{mode}", method = RequestMethod.GET)
	public Map getPartyAssessmentInfo(@PathVariable("mode") String mode, RedirectAttributes redirectAttributes)
			throws ParseException {
		Map map = new HashMap();
		map = organizeLifeService.getQd(mode);

		return map;
	}

}